package com.HeJing.对象数组相关;

/**
 * ClassName: StudentTest
 * Package: com.HeJing.对象数组相关
 * Description:
 *      创建20个学生对象，学号为1到20，年级和成绩有随机数确定
 *      问题1: 打印出三年级的学生信息
 *      问题2: 使用冒泡排序按照学生成绩排序，并遍历所有学生信息。
 * @Author: HeJing
 * @Create: 2023-03-22 16:11
 * @Version: 1.0
 */
public class StudentTest {
    public static void main(String[] args){
        // 创建对象数组: Student[]
        Student[] students = new Student[20];

        // 使用循环给数组元素赋值
        for(int i = 0; i < students.length; i++){
            students[i] = new Student();
            // 给每一个学生对象的number, state, score 赋随机值
            students[i].number = i + 1001;
            students[i].state = (int)(Math.random() * 6) + 1;   // state: 1-6 年级
            students[i].score = (int)(Math.random() * 100 - 50 + 1) + 50;  // score: 50-100分
        }
        // 需求1: 打印出3年级(state值为3)的学生信息
        for(int i = 0; i < students.length; i++){
            if(students[i].state == 3) {
                String info = students[i].show();
                System.out.println(info);
            }
        }

        System.out.println("\n*******************************************");
        System.out.println("*******************************************\n");

        // 需求2: 使用冒泡排序按学生成绩排序，并遍历所有学生信息:
        for(int i = 0; i < students.length - 1; i++){
            for(int j = 0; j < students.length - 1 - i; j++){
                if(students[j].score > students[j + 1].score) {
                    Student stu = new Student();
                    // 这种方式太过笨拙!!
//                    stu.number = students[j].number;
//                    stu.state = students[j].state;
//                    stu.score = students[j].score;
//
//                    students[j].number = students[j + 1].number;
//                    students[j].state = students[j + 1].state;
//                    students[j].score = students[j + 1].score;
//
//                    students[j + 1].number = stu.number;
//                    students[j + 1].state = stu.state;
//                    students[j + 1].score = stu.score;

                    // 改:
                    stu = students[j];
                    students[j] = students[j + 1];
                    students[j + 1] = stu;
                }
            }
        }

        // 遍历所有学生信息:
        for(int i = 0; i < students.length; i++) {
            String info = students[i].show();
            System.out.println(info);
        }


    }
}





























